import { createSlice } from '@reduxjs/toolkit';
import { getTimeZone } from 'react-native-localize';

export type IPAddressInfo = {
  ip: string;
  network: string;
  version: string;
  city: string;
  region: string;
  region_code: string;
  country: string;
  country_name: string;
  country_code: string;
  country_code_iso3: string;
  country_capital: string;
  country_tld: string;
  continent_code: string;
  in_eu: boolean;
  postal: null;
  latitude: number;
  longitude: number;
  timezone: string;
  utc_offset: string;
  country_calling_code: string;
  currency: string;
  currency_name: string;
  languages: string;
  country_area: number;
  country_population: number;
  asn: string;
  org: string;
};

export type GlobalState = {
  ipInfo: IPAddressInfo;
  isChineseUser: boolean;
};

const initialState: GlobalState = {
  ipInfo: {} as IPAddressInfo,
  isChineseUser: false,
};

const globalSlice = createSlice({
  name: 'globalSlice',
  initialState,
  reducers: {
    updateIPAddressInfo: (state) => {
      //   fetch('https://ipapi.co/json/')
      //     .then((res) => res.json())
      //     .then((data) => {
      //       state.ipInfo = data;
      //       state.isChineseUser = data.country_code === 'CN';
      //     })
      //     .catch((reason) => {
      //       console.log('无法获取用户IP地址信息，原因是：', reason);
      //     });
      const timezone = getTimeZone();
      state.isChineseUser =
        timezone === 'Asia/Shanghai' ||
        timezone === 'Asia/Chongqing' ||
        timezone === 'Asia/Hong_Kong' ||
        timezone === 'Asia/Beijing';
    },
  },
});

export const { updateIPAddressInfo } = globalSlice.actions;

export default globalSlice.reducer;
